<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          size="small"
          placeholder="请输入员工姓名"
          type="text"
          prefix-icon="el-icon-search"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          :props="defaultProps"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="operate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="'import-excel'" size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button v-permission="'export-excel'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="userList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment ===1">正式</span>
              <span v-else-if="row.formOfEmployment ===2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">编辑</el-button>
              <el-button size="mini" type="text" @click="btnRoleClick(row.id)">角色</el-button>
              <el-popconfirm title="确定删除吗？" @onConfirm="confirmDelete(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height:60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev,pager,next"
            :total="total"
            background
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel v-dialogDrag :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 添加展示分配权限的弹框 -->
    <el-dialog :visible.sync="showRoleDialog" title="角色权限">
      <!-- 放置要分配的角色 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnAssignRole">确定</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportExcel, delUser, getEnableRoleList, getEmployeeDetail, assionRole } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      total: 0, // 记录员工的总数
      // 存储用户列表
      userList: [],
      showExcelDialog: false, // 展示导入Excel的弹框
      showRoleDialog: false, // 展示角色的弹框
      roleList: [], // 存储角色列表
      roleIds: [], // 存储选择的角色id
      currentUserId: '' // 存储当前点击用户的id

    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取左侧树
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 注意：需要给树组件设置 node-key 属性 否则 setCurrentKey 方法不知道设置那个字段值
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 调用加载员工列表数据
      this.getEmployeeList()
    },
    // 切换节点时候再次记录 id
    selectNode(node) {
      this.queryParams.departmentId = node.id
      // 点击左侧树把右侧列表页数重置为第一页
      this.queryParams.page = 1
      // 调用加载员工列表数据
      this.getEmployeeList()
    },
    // 获取用户列表数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.userList = rows
      this.total = total
      // console.log(this.userList, total)
    },
    // 分页改变
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList()
    },
    // 模糊搜索功能 支持防抖查询
    changeValue() {
      // 单位时间内只执行最后一次
      // this 的实例上赋值了一个 timer 属性
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出Excel功能
    async exportEmployee() {
      const res = await exportExcel()
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息.xlsx')
    },
    // 删除员工
    async confirmDelete(id) {
      await delUser(id)
      this.$message.success('删除员工成功')
      // 重新加载数据，需要判断当前是第几页
      if (this.userList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
    },
    // 展示角色弹框
    async btnRoleClick(id) {
      // 获取可用权限列表
      this.roleList = await getEnableRoleList()
      // 根据当前点击的用户id获取用户详情数据拿到当前用户已经拥有的权限id数组
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    // 给员工分配角色
    async btnAssignRole() {
      await assionRole({ id: this.currentUserId, roleIds: this.roleIds })
      this.$message.success('分配权限成功')
      this.showRoleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
  .app-container{
    background: #fff;
    display: flex;
    .left{
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
      .el-input{
        margin-bottom:10px;
      }
    }
    .right{
      flex:1;
      padding: 20px;
      .operate-tools{
        margin: 10px;
      }
      .username{
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04c9be;
        font-size: 12px;
        display: inline-block;
      }
    }
  }
</style>
